import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
/*import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'*/

/*引入element 新方式 */
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'

/*import Mock from './mock'
Mock.bootstrap();*/

//引入axios
import axios from 'axios'
//配置axios的全局基本路径，访问后端接口使用8080
axios.defaults.baseURL='http://localhost:8080/'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

//引入自定义Vue指令
import mydirctive from './common/js/permission'


import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})


//======================路由的前端拦截器【拦截不到后端的请求】====================//
//拦截受限资源的访问， 如直接在地址栏输入utl访问受限资源
router.beforeEach((to, from, next) => {
  //如果要访问的路径是/login 或者/register则认为是没有登陆过
  if (to.path == '/login' || to.path == "/shopRegister") {

    //清除之前的登录信息
    localStorage.removeItem("token");
    localStorage.removeItem("logininfo");
    localStorage.removeItem("permissions");
    localStorage.removeItem("menus");

    next();//放行
  }else{
    //访问其他的受限路径，判断是否登录
    let logininfo = localStorage.getItem('logininfo');
    if (logininfo) {
      //登录过直接放行
      next();
    } else {
      //没有登录，则跳转到登录页面
      next({path: '/login'});//跳转到login
    }
  }
})


/**
 * axios 前置拦截器
 * 拦截前端发送的异步axios请求，给请求中添加一些用于判断是否登录的信息如：token或者logininfo
 */
//======================axios的前置拦截器【拦截调用后端的请求】====================//
axios.interceptors.request.use(res=>{
  let token = localStorage.getItem("token");

  //将token放入请求头中，作为参数传递到后台， 用于后台验证是否登录（以token为键从redis中取值）
  if(token){
    res.headers["token"] = token;
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//


//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
//接收后台登录拦截器返回的信息
axios.interceptors.response.use(res => {
  //后端响应的是没有登录的信息
  if (!res.data.success && "noLogin" === res.data.message) {
    localStorage.removeItem("token");
    localStorage.removeItem("logininfo");
    localStorage.removeItem("permissions");
    localStorage.removeItem("menus");
    //没有登录则跳转到登录页面
    router.push({path: '/login'});
  } else if (!res.data.success && "noPermission" === res.data.message) {
    alert("你没有权限访问该资源");
  } else if (!res.data.success && "error" === res.data.message) {
    alert("系统繁忙，请稍后重试");
  } else if (!res.data.success && "timeout" === res.data.message) {
    localStorage.removeItem("token");
    localStorage.removeItem("logininfo");
    localStorage.removeItem("permissions");
    localStorage.removeItem("menus");
    alert("登录超时");
    //router.push({path: '/login'});
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//前置路由 配置了就需要登录才能访问后台
/*router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})*/

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')



//处理页面刷新动态路由失效问题
initIndexRouters();
function initIndexRouters(){
  if(!localStorage.menus){
    return;
  }
  //防止重复配置路由：5就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
  if(router.options.routes.length>5){
    return;
  }
  let menus = localStorage.getItem('menus');
  menus = JSON.parse(menus);
  let tempRouters = [];
  menus.forEach(menu=>{
    let indexRouter = {
      path: '/',
      iconCls: menu.icon,
      name: menu.name,
      component: resolve => require(['@/views/Home'], resolve),
      children: []
    }
    menu.children.forEach(cMenu=>{
      let cr = {
        path: cMenu.url,
        name: cMenu.name,
        component: resolve => require(['@/views/'+cMenu.component], resolve)
      }
      indexRouter.children.push(cr)
    })
    tempRouters.push(indexRouter)
    router.options.routes.push(indexRouter)
  })
  //动态路由配置
  router.addRoutes(tempRouters);
}